package com.mspbots.script.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class RabbitConfiguration {

    @Autowired
    private AmqpAdmin amqpAdmin;


    @Bean
    public void declareEvent() {
        Exchange eventExchange = ExchangeBuilder.fanoutExchange("msp.trigger.event").build();
        this.amqpAdmin.declareExchange(eventExchange);

        Queue queue = QueueBuilder.durable("trigger.event").build();
        this.amqpAdmin.declareQueue(queue);
        this.amqpAdmin.declareBinding(BindingBuilder.bind(queue)
                .to(eventExchange).with("trigger.event").noargs());

    }

    @Bean("customContainerFactory")
    public SimpleRabbitListenerContainerFactory containerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConcurrentConsumers(15);
        factory.setMaxConcurrentConsumers(30);
        configurer.configure(factory, connectionFactory);
        return factory;
    }


    @Bean
    public MessageConverter rabbitMessageConverter(ObjectMapper objectMapper) {
        return new Jackson2JsonMessageConverter(objectMapper);
    }
}
